// xc_lshop/wholesale/purchaseorder/index.js
var actcart = require('../../../xc/sys/purchaseorder')

Page({
  mixins: [require('../../../xc/mixins/basicMixin')],

  /**
   * 页面的初始数据
   */
  data: {
    cartlist:[],
    isedit: false,
    sumprice: 0,
    type:0,//种类
    nums:0,//件数
    ischeckedall: false,
    folddata: {
      // 226:true
    }, //折叠数据 默认展开属性false  
  },
  xcloaddata: function (options, config) {


    var app = getApp();
    var that = this;
    app.xc_sys_config.authop.oppower("login").then(function (res) {
      if (res.status == 1) {
        that.loadcartdata()
      }
    })

  },
  onclickedit(){
    console.log(this.data.isedit) 
    this.setData({
      isedit:!this.data.isedit
    }) 
  },
  loadcartdata() {
    var that = this;
    this.showfolddata()
    actcart.loadcartPromise().then(function (ret) {
        if (ret.code == "success") {
          var updatemdoel = {};
          updatemdoel["cartlist"] = ret.data;
          console.log("updatemdoel")

          console.log(updatemdoel)
          // that.data.exinfo = ret["exinfo"]
          // updatemdoel["cartlist"] = that.setlimitnum(updatemdoel["cartlist"])

          that.setData(updatemdoel)
          that.price()
          // that.vildchosedall()
        }

      }
    )
  },
  price() {
    console.log(this.data.cartlist)
    var cartlist = this.data.cartlist;
    var sumprice = 0;
    var type = 0;
    var nums = 0;

    for (var i in cartlist) {
      // if (cartlist[i]['guigetype'] == 1) {
        for (var a in cartlist[i]['attrs']) {
          if (cartlist[i]['attrs'][a]['ischecked']) {
            type +=1;
            nums +=cartlist[i]['attrs'][a]['num'];
            sumprice += cartlist[i]['attrs'][a]['wsprice'] * cartlist[i]['attrs'][a]['num']
          }
        }
      // }
    }

    this.setData({
      sumprice: sumprice,
      nums:nums,
      type:type
    })
  },
  showattr(e) {
    var id = e.currentTarget.dataset.id;
    var name = 'folddata.' + id

    this.setData({
      [name]: !this.data.folddata[id]
    })

  },
  choseall() {
    var ischeckedall = !this.data.ischeckedall;
    var cartlist = this.data.cartlist;
    var sumprice = 0;

    for (var i in cartlist) {
        for (var a in cartlist[i]['attrs']) {
          if (ischeckedall) {
            if (!cartlist[i]['attrs'][a]['ischecked']) {
              actcart.setchk(cartlist[i]['id'], a, true)
            }
            cartlist[i]['attrs'][a]['ischecked'] = true;
            sumprice += cartlist[i]['attrs'][a]['wsprice'] * cartlist[i]['attrs'][a]['num']
          } else {
            if (cartlist[i]['attrs'][a]['ischecked']) {
              actcart.setchk(cartlist[i]['id'], a, false)
            }
            cartlist[i]['attrs'][a]['ischecked'] = false;
          }
        }
    }
    this.setData({
      ischeckedall: ischeckedall,
      cartlist: cartlist,
      sumprice: sumprice
    })
  },
  onSinglechoose(e) {
    var index = e.currentTarget.dataset.index;
    var key = e.currentTarget.dataset.key;
    var id = e.currentTarget.dataset.id;

    var name = 'cartlist[' + index + ']attrs.' + key + '.ischecked'
    actcart.setchk(id, key, !this.data.cartlist[index].attrs[key].ischecked)

    this.setData({
      [name]: !this.data.cartlist[index].attrs[key].ischecked
    })

    this.price()
  },
  numchange(ev) {
    console.log("ffff")
    var num = parseInt(ev.detail)
    var dataset = ev.currentTarget.dataset
    var id = dataset.id
    var index = dataset.index
    var key = dataset.key

    actcart.setnum(id, key, num)


    var cartlist = this.data.cartlist
    if (num == 0) {
      delete cartlist[index]['attrs'][key];
      if (Object.keys(cartlist[index]['attrs']).length == 0) {
        cartlist.splice(index, 1)
        if(this.data.folddata[id]){
          delete this.data.folddata[id];
        }
      }
    } else {
      cartlist[index]['attrs'][key]["num"] = num;
      if (!cartlist[index]['attrs'][key]["ischecked"]) {
        cartlist[index]['attrs'][key]["ischecked"] = true
      }
    }

    var updatemodel = {};
    updatemodel["cartlist"] = cartlist;

    this.setData(updatemodel)
    this.price()


  },
  onClickButton() {
    if (this.data.isedit) {
      var cartlist=this.data.cartlist
      var ilen = cartlist.length - 1
      var delnum = 0
      var newcartlist=[] 
      for (; ilen >= 0; ilen--) {
        for(var key in cartlist[ilen]['attrs']){
          if (cartlist[ilen]['attrs'][key].ischecked) {
            delete cartlist[ilen]['attrs'][key]
            actcart.setnum(cartlist[ilen]['id'],key, 0)
            delnum++
          }
        }
        if(Object.keys(cartlist[ilen]['attrs']).length>0){

          newcartlist.push(cartlist[ilen])
        }else{
          if(this.data.folddata[cartlist[ilen]["id"]]){
            delete this.data.folddata[cartlist[ilen]["id"]]
          }
        }  
      }
      console.log("gvgggg")
      console.log(newcartlist)
      if (delnum > 0) {
        this.setData({
          cartlist: newcartlist
        })
      }
      
      

    } else {
      var cartdata = [];

      this.data.cartlist.forEach(item => {
        var attrs={}
        for(var i in item.attrs){
          if (item.attrs[i].ischecked) {
            if(item.attrs[i].num>0){
              attrs[i]=item.attrs[i]
            }
          }
        }
        if(Object.keys(attrs).length>0){
          item['attrs']=attrs
          cartdata.push(item)
        }
      })
      if (cartdata.length < 1) {

        wx.showToast({
          icon:"error",
          title: '请选择产品',
        })
      } else {
        console.log("cartdata")
        console.log(cartdata)
        console.log(JSON.stringify(cartdata) )

        var app = getApp();
       
        app.globalData.temcart["data"] = cartdata
        wx.navigateTo({
          url: '/' + app.globalData.xcsys.m + '/shop/paycore/payinfo?iscart=1&iswholesale=1'
        })
      }





      console.log("提交模式")
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  showfolddata(){
    var that=this;
    wx.getStorage({
      key: "folddata",
      success: function (et) {
        if(et.data){
          that.setData({
            folddata:JSON.parse(et.data)
          })
        }
      }
    })
  },
  savefolddata(){
    wx.setStorage({
      key: "folddata",
      data: JSON.stringify(this.data.folddata),
      success: function (et) {}
    })
  },
  /** 
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log("onHide")
    this.savefolddata()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log("onUnload")
    this.savefolddata()

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})